package com.crazypos.security;

import com.crazypos.common.utils.JWTTokenUtil;
import com.crazypos.pojo.RoleEntity;
import com.crazypos.pojo.UserEntity;
import com.crazypos.security.entity.UserDetailEntity;
import com.crazypos.security.service.UserDetailService;
import com.crazypos.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 自定义登录接口
 */
@Component
public class UserAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private IUserService userService;

    @Autowired
    private UserDetailService userDetailService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String account = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();
        UserDetailEntity loginUser = userDetailService.loadUserByUsername(account);
//        UserEntity loginUser = userService.getUserByAccnount(account);

        if (loginUser == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        // 我们还要判断密码是否正确，这里我们的密码使用BCryptPasswordEncoder进行加密的
        if (!new BCryptPasswordEncoder().matches(password, loginUser.getPassword())) {
            throw new BadCredentialsException("密码不正确");
        }

        // 角色集合
        Set<GrantedAuthority> authorities = new HashSet<>();
        List<RoleEntity> roles = userService.selectRolesByUserId(loginUser.getId());

        for (RoleEntity role :
                roles) {
            authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getName()));
        }
        loginUser.setAuthorities(authorities);

        return new UsernamePasswordAuthenticationToken(loginUser, loginUser.getPassword(), authorities);
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
